package in.muton.edushare.panels.assignment;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.panels.upload.MultipleFileUploadButtonPanel;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.dao.AssignmentsDAO;
import com.edushare.common.dao.FilesUploadedDAO;
import com.edushare.common.dao.UserAssignmentLinkDAO;
import com.edushare.common.vo.Assignments;
import com.edushare.common.vo.FileDirectories;
import com.edushare.common.vo.FilesUploaded;
import com.edushare.common.vo.UserAssignmentLink;

public class AssigneeSubmissionPanel extends EdusharePanel {

	private static final long serialVersionUID = -304775268854907331L;
	private static Log log = LogFactory.getLog(AssigneeSubmissionPanel.class);
	private IModel<Assignments> model;
	private CayenneModel<FileDirectories> fileDirModel;
	private final WebMarkupContainer filesDiv = new WebMarkupContainer("filesDiv");
	
	public AssigneeSubmissionPanel(String id, IModel<Assignments> assnModel){
		super(id, assnModel);
		this.model = assnModel;
		loadPanel();
	}

	private void loadPanel() {
		
		add(new Label("submStatus", Assignments.getStatusAsString(model.getObject().getStatus()).toUpperCase()));
		
		Form<Void> form = new Form<Void>("myFilesForm");
		add(form);
		
		FileDirectories submissionDir = 
			new AssignmentsDAO(getORMInterface())
				.getSubmissionsDirectory(model.getObject());
		this.fileDirModel = new CayenneModel<FileDirectories>(submissionDir);
		filesDiv.setOutputMarkupId(true);
		form.add(filesDiv);
		
		ListView<FilesUploaded> myFilesCont = 
			new ListView<FilesUploaded>("myFilesCont", new PropertyModel<List<FilesUploaded>>(this, "assigneeFiles")){

				private static final long serialVersionUID = 2862054633545139476L;

				@Override
				protected void populateItem(final ListItem<FilesUploaded> item) {
					item.add(
							new ExternalLink(
									"myFileLink", 
									new PropertyModel<String>(item.getModel(),"fileDownloadUrl"), 
									new PropertyModel<String>(item.getModel(),"fileOrigName")));
					
					if(model.getObject().isSubmissionAllowed()){
						item.add(new DelFrag("delLink", this, item.getModel()));
					}else{
						item.add(new EmptyPanel("delLink"));
					}
					
				}
			
			};
			
		filesDiv.add(myFilesCont);
		
		
		
		if(model.getObject().isSubmissionAllowed() && new UserAssignmentLinkDAO(getORMInterface()).isAssignee(getLoggedInUser())){
			//include upload fragment
			add(new UploadFrag("uploadDiv", this));
		}else if(!new UserAssignmentLinkDAO(getORMInterface()).isAssignee(getLoggedInUser())){
			add(new NotAllowedFrag("uploadDiv", this));
		}else{
			//include warning fragment
			add(new WarningFrag("uploadDiv", this));
		}
		
		// show files
		
		//download all link
	}
	
	/** no permission for non-assignee */
	public class NotAllowedFrag extends Fragment{

		private static final long serialVersionUID = -1771562665415414771L;

		public NotAllowedFrag(String id,MarkupContainer container) {
			super(id, "notAllowedFrag", container);
		}
		
	}
	
	/** Upload Fragment: shows warning */
	public class WarningFrag extends Fragment{

		private static final long serialVersionUID = -3512692502427560794L;

		public WarningFrag(String id,MarkupContainer container) {
			super(id, "warningFrag", container);
		}
		
	}
	
	/** Upload Fragment: shows upload button */
	public class UploadFrag extends Fragment{

		private static final long serialVersionUID = -7558771323791724104L;
		
		public UploadFrag(String id, MarkupContainer container) {
			super(id, "uploadFrag", container);
			
			if(model.getObject().getStatus() == Assignments.ASSIGNMENT_STATUS_LATE){
				Label warn = 
					new Label("warnLate","<strong>Please note:</strong> Any upload done now will mark your " +
						"submission for this assignment as \"LATE SUBMISSION\" and will be evaluated accordingly.");
				warn.setEscapeModelStrings(false);
				warn.add(new AttributeAppender("class", true, new Model<String>("es-warn"), " "));
				warn.add(new AttributeAppender("style", true, new Model<String>("width:650px"), "; "));
				add(warn);
			}else{
				add(new EmptyPanel("warnLate"));
			}
			
			Form<Void> form = new Form<Void>("asnUploadForm");
			add(form);
			form.add(
				new MultipleFileUploadButtonPanel("asnUserUploadPanel", AssigneeSubmissionPanel.this.fileDirModel){
				
					private static final long serialVersionUID = -2174574207659828313L;

					@Override
					public void onUploadWindowClose(AjaxRequestTarget target) {
						log.debug("Files Uploaded:: "+ EduShareSession.get().getFilesUploadedThisSession() +" - "+getFilesUploadedBeforeButtomClicked());
						//update link table if any files uploaded
						if(EduShareSession.get().getFilesUploadedThisSession()- getFilesUploadedBeforeButtomClicked()>0){
							UserAssignmentLink ual =
								new UserAssignmentLinkDAO(getORMInterface())
										.getUserAssignmentLink(
												getLoggedInUser(), 
												AssigneeSubmissionPanel.this.model.getObject());
							ual.setLastUpdated(new Date());
							ual.setStatus(ual.getSubmissionStatus(AssigneeSubmissionPanel.this.model.getObject()));
							getORMInterface().commitAllChanges();
						}
						target.addComponent(AssigneeSubmissionPanel.this.filesDiv);
					}
			});
		}
	}
	
	public List<FilesUploaded> getAssigneeFiles(){
		return new FilesUploadedDAO(getORMInterface()).getFilesUploadedByUser(fileDirModel.getObject(), getLoggedInUser());
	}
	
	/** link to delete file */
	public class DelFrag extends Fragment{

		private static final long serialVersionUID = 8258068488106412534L;

		public DelFrag(String id, MarkupContainer markupProvider, final IModel<FilesUploaded> fileModel) {
			super(id, "delFrag", markupProvider, fileModel);
			add(new SubmitLink("delMyFile"){
	
					private static final long serialVersionUID = -6714186889658179992L;
	
					@Override
					public void onSubmit() {
						if(fileModel.getObject()!=null){
							new FilesUploadedDAO(getORMInterface()).deleteFileUploaded(fileModel.getObject());
							getORMInterface().commitAllChanges();
						}
					}
					
				});
		}
		
	}
	
}
